package com.blog.service.impl;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.blog.feign.ProductFeignClient;
import com.blog.order.Order;
import com.blog.product.Product;
import com.blog.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.math.BigDecimal;
import java.util.Arrays;

/**
 * @ClassName OrderServiceImpl
 * @Destription
 * @Author 天堂小野花
 * @Date 2025/7/31  23:48
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    RestTemplate restTemplate;
    @Resource
    ProductFeignClient productFeignClient;
    @SentinelResource(value = "createOrder",fallback = "createOrderFallback")
    @Override
    public Order createOrder(Integer productId, Integer userId) {
        //使用restTemplate获取数据
        //Product product = getProductFromRemote(productId);
        //使用OpenFeign获取数据
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1);
        order.setUserId(userId);
        order.setNickName("测试");
        order.setAddress("江苏");
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setProductList(Arrays.asList(product));
        return order;
    }
    //远程方法的兜底回调
    public Order createOrderFallback(Integer productId, Integer userId, Throwable e) {
        Order order = new Order();
        order.setId(0);
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息："+e.getClass());
        order.setTotalAmount(new BigDecimal(0));
        order.setProductList(null);
        return order;
    }
    private Product getProductFromRemote(Integer productId){
        String url ="http://service-product/product/"+productId;
        Product product =restTemplate.getForObject(url, Product.class);
        return product;
    }
}
